package org.eiahe.hr.employeeRelation.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.ehe.common.core.utils.MapstructUtils;
import org.ehe.system.domain.HrEmployee;
import org.ehe.system.mapper.HrEmployeeMapper;
import org.eiahe.hr.attendance.domain.AttendanceAlert;
import org.eiahe.hr.attendance.domain.bo.AttendanceAlertBo;
import org.eiahe.hr.employeeRelation.domain.RewardPunishmentApplication;
import org.eiahe.hr.employeeRelation.domain.RewardPunishmentRecord;
import org.eiahe.hr.employeeRelation.domain.bo.RewardPunishmentApplicationBo;
import org.eiahe.hr.employeeRelation.domain.bo.RewardPunishmentRecordBo;
import org.eiahe.hr.employeeRelation.domain.vo.RewardPunishmentApplicationVo;
import org.eiahe.hr.employeeRelation.domain.vo.RewardPunishmentRecordVo;
import org.eiahe.hr.employeeRelation.mapper.RewardPunishmentApplicationMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.eiahe.hr.employeeRelation.mapper.RewardPunishmentRecordMapper;
import org.eiahe.hr.employeeRelation.service.IRewardPunishmentService;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 奖惩管理服务实现类
 *
 * @author zhangnn
 */
@RequiredArgsConstructor
@Service
public class RewardPunishmentServiceImpl implements IRewardPunishmentService {

    private final RewardPunishmentApplicationMapper applicationMapper;
    private final RewardPunishmentRecordMapper recordMapper;
    private final HrEmployeeMapper employeeMapper;

    /**
     * 查询奖惩申请列表
     *
     * @param bo 奖惩申请业务对象
     * @return 奖惩申请列表
     */
    @Override
    public List<RewardPunishmentApplicationVo> selectRewardPunishmentApplicationList(RewardPunishmentApplicationBo bo) {
        LambdaQueryWrapper<RewardPunishmentApplication> wrapper = Wrappers.lambdaQuery();
        // 根据需要添加查询条件
        return applicationMapper.selectVoList(wrapper);
    }

    /**
     * 查询奖惩申请列表(分页)
     *
     * @param bo        奖惩申请业务对象
     * @param pageQuery 分页参数
     * @return 奖惩申请分页列表
     */
    @Override
    public TableDataInfo<RewardPunishmentApplicationVo> selectRewardPunishmentApplicationList(
            RewardPunishmentApplicationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<RewardPunishmentApplication> lqw = Wrappers.lambdaQuery();
        // 根据需要添加查询条件
        IPage<RewardPunishmentApplicationVo> page = applicationMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    /**
     * 通过申请ID查询奖惩申请信息
     *
     * @param applicationId 申请ID
     * @return 奖惩申请信息
     */
    @Override
    public RewardPunishmentApplicationVo selectRewardPunishmentApplicationById(Long applicationId) {
        return applicationMapper.selectVoById(applicationId);
    }

    /**
     * 新增奖惩申请
     *
     * @param bo 奖惩申请业务对象
     * @return 结果
     */
    @Override
    public Boolean insertRewardPunishmentApplication(RewardPunishmentApplicationBo bo) {
        RewardPunishmentApplication application = MapstructUtils.convert(bo, RewardPunishmentApplication.class);
        return applicationMapper.insert(application) > 0;
    }

    /**
     * 修改奖惩申请
     *
     * @param bo 奖惩申请业务对象
     * @return 结果
     */
    @Override
    public Boolean updateRewardPunishmentApplication(RewardPunishmentApplicationBo bo) {
        RewardPunishmentApplication application = MapstructUtils.convert(bo, RewardPunishmentApplication.class);
        return applicationMapper.updateById(application) > 0;
    }

    /**
     * 批量删除奖惩申请
     *
     * @param applicationIds 需要删除的申请ID数组
     * @return 结果
     */
    @Override
    public Boolean deleteRewardPunishmentApplicationByIds(Long[] applicationIds) {
        return applicationMapper.deleteBatchIds(Arrays.asList(applicationIds)) > 0;
    }

    /**
     * 查询奖惩记录列表
     *
     * @param bo 奖惩记录业务对象
     * @return 奖惩记录列表
     */
    @Override
    public List<RewardPunishmentRecordVo> selectRewardPunishmentRecordList(RewardPunishmentRecordBo bo) {
        LambdaQueryWrapper<RewardPunishmentRecord> wrapper = Wrappers.lambdaQuery();
        // 根据需要添加查询条件
        List<RewardPunishmentRecordVo> rewardPunishmentRecordVos = recordMapper.selectVoList(wrapper);
        rewardPunishmentRecordVos.forEach(p->{
            Long employeeId = p.getEmployeeId();
            HrEmployee hrEmployee = employeeMapper.selectById(employeeId);
            if(Objects.nonNull(hrEmployee)){
                p.setEmployeeName(hrEmployee.getEmployeeName());
            }
        });
        return rewardPunishmentRecordVos;
    }

    /**
     * 查询奖惩记录列表(分页)
     *
     * @param bo        奖惩记录业务对象
     * @param pageQuery 分页参数
     * @return 奖惩记录分页列表
     */
    @Override
    public TableDataInfo<RewardPunishmentRecordVo> selectRewardPunishmentRecordList(RewardPunishmentRecordBo bo,
            PageQuery pageQuery) {
        LambdaQueryWrapper<RewardPunishmentRecord> lqw = buildQueryWrapper(bo);
        // 根据需要添加查询条件
        IPage<RewardPunishmentRecordVo> page = recordMapper.selectVoPage(pageQuery.build(), lqw);
        page.getRecords().forEach(p->{
            Long employeeId = p.getEmployeeId();
            HrEmployee hrEmployee = employeeMapper.selectById(employeeId);
            if(Objects.nonNull(hrEmployee)){
                p.setEmployeeName(hrEmployee.getEmployeeName());
            }
        });
        return TableDataInfo.build(page);
    }
    private LambdaQueryWrapper<RewardPunishmentRecord> buildQueryWrapper(RewardPunishmentRecordBo bo) {
        LambdaQueryWrapper<RewardPunishmentRecord> lqw = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(bo.getEmployeeName())) {
            List<HrEmployee> employees = employeeMapper.selectList(
                Wrappers.lambdaQuery(HrEmployee.class)
                    .like(HrEmployee::getEmployeeName, bo.getEmployeeName()));
            List<String> employeeNos = Optional.ofNullable(employees)
                .orElse(Collections.emptyList())
                .stream()
                .map(HrEmployee::getEmployeeNo)
                .collect(Collectors.toList());

            if (CollUtil.isEmpty(employeeNos)) {
                lqw.eq(RewardPunishmentRecord::getEmployeeNo, -1);
            } else {
                lqw.in(RewardPunishmentRecord::getEmployeeNo, employeeNos);
            }
        }
        lqw.eq(StringUtils.isNotBlank(bo.getEmployeeNo()), RewardPunishmentRecord::getEmployeeNo, bo.getEmployeeNo());
        lqw.eq(StringUtils.isNotBlank(bo.getRewardPunishmentType()), RewardPunishmentRecord::getRewardPunishmentType,
            bo.getRewardPunishmentType());
        return lqw;
    }
    /**
     * 通过记录ID查询奖惩记录
     *
     * @param recordId 记录ID
     * @return 奖惩记录
     */
    @Override
    public RewardPunishmentRecordVo selectRewardPunishmentRecordById(Long recordId) {
        return recordMapper.selectVoById(recordId);
    }

    /**
     * 新增奖惩记录
     *
     * @param bo 奖惩记录业务对象
     * @return 结果
     */
    @Override
    public Boolean insertRewardPunishmentRecord(RewardPunishmentRecordBo bo) {
        RewardPunishmentRecord record = MapstructUtils.convert(bo, RewardPunishmentRecord.class);
        if (record.getRecordId() != null) {
            // 若提供了ID，则视为更新统一表中的记录字段
            return recordMapper.updateById(record) > 0;
        }
        // 无ID则按新增处理（统一表中新增一行）
        return recordMapper.insert(record) > 0;
    }

    /**
     * 修改奖惩记录
     *
     * @param bo 奖惩记录业务对象
     * @return 结果
     */
    @Override
    public Boolean updateRewardPunishmentRecord(RewardPunishmentRecordBo bo) {
        RewardPunishmentRecord record = MapstructUtils.convert(bo, RewardPunishmentRecord.class);
        return recordMapper.updateById(record) > 0;
    }

    /**
     * 批量删除奖惩记录
     *
     * @param recordIds 需要删除的记录ID数组
     * @return 结果
     */
    @Override
    public Boolean deleteRewardPunishmentRecordByIds(Long[] recordIds) {
        return recordMapper.deleteBatchIds(Arrays.asList(recordIds)) > 0;
    }

    /**
     * 审批通过：写入审批信息并补齐记录字段
     */
    @Override
    public Boolean approveRewardPunishment(RewardPunishmentApplicationBo bo) {
        if (bo == null || bo.getApplicationId() == null) {
            return false;
        }
        // 按 applicationId（实际为统一表主键id）更新指定字段，避免把未传字段更新为null
        com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<RewardPunishmentApplication> update = Wrappers
                .lambdaUpdate();
        update.eq(RewardPunishmentApplication::getApplicationId, bo.getApplicationId())
                .set(RewardPunishmentApplication::getApproverId, bo.getApproverId())
                .set(RewardPunishmentApplication::getApprovalTime, new Date())
                .set(RewardPunishmentApplication::getApprovalRemark, bo.getApprovalRemark())
                .set(RewardPunishmentApplication::getApprovalStatus, "1") //已通过
                .set(bo.getRecordTime() != null, RewardPunishmentApplication::getRecordTime, bo.getRecordTime())
                .set(bo.getProcessingResult() != null && !bo.getProcessingResult().isEmpty(),
                        RewardPunishmentApplication::getProcessingResult, bo.getProcessingResult())
                .set(bo.getImpact() != null && !bo.getImpact().isEmpty(),
                        RewardPunishmentApplication::getImpact, bo.getImpact());
        return applicationMapper.update(null, update) > 0;
    }


    /**
     * 审批拒绝
     */
    @Override
    public Boolean rejectRewardPunishment(RewardPunishmentApplicationBo bo) {
        if (bo == null || bo.getApplicationId() == null) {
            return false;
        }
        com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<RewardPunishmentApplication> update = Wrappers
            .lambdaUpdate();
        update.eq(RewardPunishmentApplication::getApplicationId, bo.getApplicationId())
            .set(RewardPunishmentApplication::getApproverId, bo.getApproverId())
            .set(RewardPunishmentApplication::getApprovalTime, new Date())
            .set(RewardPunishmentApplication::getApprovalRemark, bo.getApprovalRemark())
            .set(RewardPunishmentApplication::getApprovalStatus, "2") //已拒绝
            .set(bo.getRecordTime() != null, RewardPunishmentApplication::getRecordTime, bo.getRecordTime())
            .set(bo.getProcessingResult() != null && !bo.getProcessingResult().isEmpty(),
                RewardPunishmentApplication::getProcessingResult, bo.getProcessingResult())
            .set(bo.getImpact() != null && !bo.getImpact().isEmpty(),
                RewardPunishmentApplication::getImpact, bo.getImpact());
        return applicationMapper.update(null, update) > 0;
    }
}
